package part10_代理模式_调用目标对象.p04_反射之动态代理;

import java.lang.reflect.InvocationTargetException;

/**
 * @ClassName: DynaProxyDemo
 * @Author: AllenSun
 * @Date: 2020/3/29 14:19
 */
public class DynaProxyDemo {
    public static void main(String[] args) {

        //（一）1-6是测试如何使用反射实例化对象
        //（1）输出类的路径
        RealSubject realSubject=new RealSubject();
        System.out.println("类.包路径："+realSubject.getClass());

        //（2）声明一个Class对象
        Class<?> clazz=null;
        //（3）准备一个路径字符串
        String path="part10_代理模式_调用目标对象.p04_反射之动态代理.RealSubject";
        //（4）Class对象实例化，反射声明RealSubject类对象
        try {
            //实例化对象最常用的形式
            clazz=Class.forName(path);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //（5）声明RealSubject类对象
        RealSubject realSubject1 = null;
        //（6）Class类对象调用newInstance方法，等于调用RealSubject构造方法来对象实例化
        try {
            //Java9之后，newInstance方法已经被弃用，改用：getDeclaredConstructor().newInstance()
            realSubject1 = (RealSubject) clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //（二）开始动态代理
        MyInvocationHandler handler=new MyInvocationHandler();
        Subject subject= (Subject) handler.bind(realSubject1);
        String info=subject.say("张三",30);
        System.out.println(info);
    }
}
